import 'package:async/async.dart';
import 'package:boss/common/common.dart';

import 'package:boss/main.dart';
import 'package:boss/models/staff.dart';
import 'package:boss/ui/page/staff/staff_page.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';

class StaffProvider extends ChangeNotifier {
  int page = 1;
  List<Staff> staffs;
  String searchWord = '';

  final GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  Future<Result<List<Staff>>> queryStaff() async {
    try {
      var response = await api.queryStaffList({'nickname': searchWord}, page: page);
      if (!response.successful()) {
        return Result.error(response.msg);
      }
      if (staffs == null) staffs = [];
      staffs.addAll(response.data.items);
      notifyListeners();
      return Result.value(response.data.items);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  Future<Result<List<Staff>>> refreshStaffList() async {
    page = 1;
    staffs = [];

    return queryStaff();
  }

  Future<Result<List<Staff>>> loadMoreStaffList() async {
    page += 1;

    return queryStaff();
  }

  firstInitData() {
    if (staffs == null) loaderPullRefreshKey.currentState.initData();
  }

  searchComplate() {
    loaderPullRefreshKey.currentState.refresh();
  }

  saveOrUpdateStaff(Staff staff) async {
    if (!RegUtil.testNotEqEmpty(staff.realname)) {
      toast('姓名不可为空，请检查');
      return;
    }

    if (!RegUtil.testNotEqEmpty(staff.username)) {
      toast('手机号不可为空，请检查');
      return;
    }

    if (!RegUtil.testPhone(staff.username)) {
      toast('请输入正确的手机号，请检查');
      return;
    }

    if (staff.roleId == null) {
      toast('请选择角色');
      return;
    }

    if (RegUtil.testNotEqEmpty(staff.idCard) && !flustars.RegexUtil.isIDCard(staff.idCard)) {
      toast('请输入正确的身份证');
      return;
    }

    try {
      showLoadingToast();

      var isUpdate = staff.userId != null;

      final result = await (isUpdate ? api.updateStaff(staff) : api.addStaff(staff));
      if (!result.successful()) {
        toast(result.msg);
        return;
      }

      toast(isUpdate ? '修改成功' : '添加成功');

      if (isUpdate) {
        var index = staffs.indexWhere((item) => item.userId == staff.userId);
        if (index != -1) {
          staffs[index] = staff;
        }
      }

      Navigator.pop(GlobalPageContext.instance.context);
    } catch (e) {
      toast(e.toString());
    } finally {
      hideLoadingToast();
    }
  }

  deleteStaff(Staff staff) async {
    showAlert(
      GlobalPageContext.instance.context,
      content: '确认删除该员工？',
      onConfirm: (context) async {
        try {
          showLoadingToast();

          var res = await api.deleteStaff(staff.userId);
          if (!res.successful()) {
            toast(res.msg);
            return;
          }
          toast('删除成功');

          staffs.removeWhere((item) => item.userId == staff.userId);
          notifyListeners();

          Navigator.popUntil(GlobalPageContext.instance.context, ModalRoute.withName(StaffPage.pageName));
        } catch (e) {
          toast(Constant.httpServeErrText);
        } finally {
          hideLoadingToast();
        }
      },
      onCancel: (context) {
        Navigator.pop(GlobalPageContext.instance.context);
      },
    );
  }

  clearData() {
    page = 1;
    staffs = null;
    searchWord = '';
  }
}
